package com.dgut.test3.service;

import com.dgut.test3.bean.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.io.IOException;
import java.io.InputStreamReader;
import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class GetData {
    /**
     * 每天凌晨1点执行计划任务，更新RegionStats成员变量
     * RegionStats成员变量储存着全球新型冠状病毒统计数据
     *
     * @throws IOException IO异常
     */
    //声明计划
    @Scheduled(cron = "${test3.Schedules.updateVirusDataCron}")
    public List<RegionStats> fetchCoronaVirusData() throws IOException {
        //存放读取出来的数据
        List<RegionStats> CV_data = new ArrayList<>();
        //csv文件的URl
        String url = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(url))
                .headers(httpHeaders -> httpHeaders.add("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();

        //获取csv文件输入流
        InputStream inputStream = body.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);
        //读取CSV文件
        Reader in = new BufferedReader(reader);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);

        for (CSVRecord record : records) {
            RegionStats stats = new RegionStats();
            stats.setState(record.get("Province/State"));
            stats.setCountry(record.get("Country/Region"));
            stats.setLatestTotalCases(Integer.parseInt((record.get(record.size()-1))));
            stats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
            CV_data.add(stats);
        }

        return CV_data;

    }

    public List<RegionStats> selectCVData(String state,String country) throws IOException {
        //存放读取出来的数据
        List<RegionStats> CV_data = new ArrayList<>();
        //csv文件的URl
        String url = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(url))
                .headers(httpHeaders -> httpHeaders.add("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        //获取csv文件输入流
        InputStream inputStream = body.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);
        //读取CSV文件
        Reader in = new BufferedReader(reader);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);

        if (!state.equals("") && !country.equals("")) {
            for (CSVRecord record : records) {
                RegionStats stats = new RegionStats();
                stats.setState(record.get("Province/State"));
                stats.setCountry(record.get("Country/Region"));
                stats.setLatestTotalCases(Integer.parseInt((record.get(record.size() - 1))));
                stats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)));
                if (state.equals( stats.getState()) && country.equals(stats.getCountry()))
                    CV_data.add(stats);
            }
        }
        if (!state.equals("") && country.equals("")) {
            for (CSVRecord record : records) {
                RegionStats stats = new RegionStats();
                stats.setState(record.get("Province/State"));
                stats.setCountry(record.get("Country/Region"));
                stats.setLatestTotalCases(Integer.parseInt((record.get(record.size() - 1))));
                stats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)));
                if (state.equals(stats.getState()))
                    CV_data.add(stats);
            }
        }
        if (state.equals("") && !country.equals("")) {
            for (CSVRecord record : records) {
                RegionStats stats = new RegionStats();
                stats.setState(record.get("Province/State"));
                stats.setCountry(record.get("Country/Region"));
                stats.setLatestTotalCases(Integer.parseInt((record.get(record.size() - 1))));
                stats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)));
                if (country.equals(stats.getCountry()))
                    CV_data.add(stats);
            }
        }
        if (state.equals("") && country.equals("")) {
            for (CSVRecord record : records) {
                RegionStats stats = new RegionStats();
                stats.setState(record.get("Province/State"));
                stats.setCountry(record.get("Country/Region"));
                stats.setLatestTotalCases(Integer.parseInt((record.get(record.size() - 1))));
                stats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)));
                CV_data.add(stats);
            }
        }
        return CV_data;
    }

}
